# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""

import logging
import os
from optparse import OptionParser

from cve_ease.helper import get_timestamp

logger = logging.getLogger('cve-ease')


def get_usage_str(usage):
    return usage + "\n(Specify the --help global option for a list of other help options)"


def sss_check_file_mode():
    file_with_security_mode = {
        "/etc/shadow": "000",
        "/etc/gshadow": "000",
        "/etc/group": "644",
        "/etc/passwd": "644",
        "/etc/sudoers": "440",
    }
    print(" -> sss_check_file_mode")

    def permission_check(file_path, permission):

        current_permission = oct(os.stat(file_path).st_mode)[-3:]
        if current_permission == permission:
            return ""
        else:
            return current_permission

    for key in file_with_security_mode:
        if not os.path.exists(key):
            print(f"    * check file [SK] {key} not found, skip")
            continue
        ret = permission_check(key, file_with_security_mode[key])
        if "" == ret:
            print(f"    * check file [OK] {key} [{file_with_security_mode[key]}]")
        else:
            print(f"    * check file [ER] {key} [{file_with_security_mode[key]}] != [{ret}]")


def handle_sss(gconfig, db_session, args):
    """[basic] System Security Scan and Fix Tool"""
    usage = "usage: %prog sss <options>"
    parser = OptionParser(usage=get_usage_str(usage))

    parser.add_option('-s', '--scan', dest='scan', action='store_true', default=False,
                      help='scan current os')
    parser.add_option('-f', '--fix', dest='fix', action='store_true', default=False,
                      help='try fix security problem')
    parser.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False,
                      help='show verbose output')

    (options, args) = parser.parse_args(args)

    if options.scan:
        begin_time = get_timestamp()
        print("")
        import sys
        import types
        module = sys.modules[__name__]
        for name in dir(module):
            if isinstance(getattr(module, name), types.FunctionType) and name.startswith("sss_check"):
                logger.debug(f"Calling {name} from {module.__name__}")
                getattr(module, name)()

        end_time = get_timestamp()
        print("")
        print(f"sss done! {begin_time} - {end_time}")
    else:
        parser.print_help()
